var rootPath = getRootPath();
var existRecord = false;
var existPRecord = false;
var existORecord = false;
var isRightICreNum = false;
var isRightPCreNum = false;
var isRightOCreNum = false;

var oriCreType;
var oriCreNum;
//picName
var i_creFrontPic = null;
var i_creReversePic = null;

var rleId;
var creType;

var isPhone = isPhoneScreen();
var param = "";

$(function() {
	
	var callbackUrl = getUrlParam("callbackUrl");//getUrlParam 带转义
	
	if(callbackUrl){
		param += "&callbackUrl=" +  encodeURIComponent(callbackUrl);
	}else{
		param += "";
	}
	
	var uid = getUrlParam("uid");//getUrlParam 带转义
	if(uid){
		param += "&uid=" +  encodeURIComponent(uid);
	}else{
		param += "";
	}
	
	
	// 滚动条置顶
	$("body").prepend('<input type="text" id="focus" size="1">');
	
	//$("#passportForm").hide();
	
	$("#i_next").removeAttr("onclick");

	$("#focus").focus();
	$("#focus").hide();

	$("#i_realNameMsg").hide();
	$("#i_creNumMsg").hide();

	$("#p_realNameMsg").hide();
	$("#p_creNumMsg").hide();

	$(".tip").hide();

	focusById();

	$("#creType").css("cursor", "pointer");

	rleId = getUrlParam("rleId");
	
	//不是去远方的身份  其他去除
	if(rleId && "gofaraway" != rleId.toLowerCase()){
		$("#creType").find("option[value='2']").remove();
	}
	
	creType = getUrlParam("creType");

	//个人认证改为"实名信息"
	if(creType < 100) {
		$("#infoTitle").html("实名信息");
	} else {
		//政府认证改为"负责人信息"
		if(102 == creType || 105 == creType) {
			$("#infoTitle").html("负责人信息");			
		}
	}

	$.ajax({
		url : rootPath + "/realNameTmp/dr/1/uid",
		method : "GET",
		success : function(data) {
			if ('0000' == data.returnCode && data.returnObject != null) {
				var obj = data.returnObject;
				//其他类型  非去远方 不回显
				if(rleId && "gofaraway" != rleId.toLowerCase() 
						&& obj.creType == 2){
					return;
				}
				
				oriCreType = obj.creType;
				oriCreNum = obj.creNum;
				$("#creType").find("option[value = '" + obj.creType + "']").prop("selected", "selected");

				if (oriCreType == "0") {
					existRecord = true;
					$("#idCardForm").show();
					$("#passportForm").hide();
					$("#otherForm").hide();

					$("#i_creNum").val(oriCreNum);
					if (oriCreNum != "") {
						isRightICreNum = true;
					}

					$("#i_realName").val(obj.realName);
					if (obj.creFrontPic != '') {
						$("#i_frontImg").prop("src",rootPath + "/file/viewimg?fileName=" + obj.creFrontPic + "&type=" + 3);
						$("#i_fwSpan").html("");
						i_creFrontPic = obj.creFrontPic;
					} else {
						i_creFrontPic = null;
					}
					if (obj.creReversePic != '') {
						$("#i_reverseImg").prop("src",rootPath + "/file/viewimg?fileName=" + obj.creReversePic + "&type=" + 3);
						$("#i_rwSpan").html("");
						i_creReversePic = obj.creReversePic;
					} else {
						i_creReversePic = null;
					}
					showIDButton();
				} else if(oriCreType == "1"){
					existPRecord = true;
					$("#idCardForm").hide();
					$("#passportForm").show();
					$("#otherForm").hide();

					$("#p_creNum").val(oriCreNum);
					$("#p_realName").val(obj.realName);
					if (obj.creFrontPic != '') {
						$("#p_frontImg").prop("src",rootPath + "/file/viewimg?fileName=" + obj.creFrontPic + "&type=" + 3);
						$("#p_fwSpan").html("");
					}
				}else {
					existORecord = true;
					$("#idCardForm").hide();
					$("#passportForm").hide();
					$("#otherForm").show();
					$("#o_creNum").val(oriCreNum);
					$("#o_realName").val(obj.realName);
					if (obj.creFrontPic != '') {
						$("#o_frontImg").prop("src",rootPath + "/file/viewimg?fileName=" + obj.creFrontPic + "&type=" + 3);
						$("#o_fwSpan").html("");
					}
				}
			}else{
				$("#idCardForm").show();
				$("#passportForm").hide();
				$("#otherForm").hide();
			}
		},
		error : function(jqXHR, textStatus, errorThrown) {
			layer.alert("error");
			$("#idCardForm").show();
			$("#passportForm").hide();
			$("#otherForm").hide();
		}
	});
	$("#creType").change(function() {
		if ($("#creType option:selected").val() == "0") { //身份证
			$("#idCardForm").css("display","block");
			$("#passportForm").css("display","none");
			$("#otherForm").css("display","none");
		} else if ($("#creType option:selected").val() == "1"){//护照
			$("#idCardForm").css("display","none");
			$("#passportForm").css("display","block");
			$("#otherForm").css("display","none");
		} else if ($("#creType option:selected").val() == "2"){//其他
			$("#idCardForm").css("display","none");
			$("#passportForm").css("display","none");
			$("#otherForm").css("display","block");
		} else { //非法
			$("#idCardForm").css("display","none");
			$("#passportForm").css("display","none");
			$("#otherForm").css("display","none");
		}

	});
	$("#i_creNum").focus(function() {
		isRightICreNum = false;
	});
	
	$("#i_creNum").blur(function() {
		checkCreNum(0);
	});
	
	$("#p_creNum").focus(function() {
		isRightPCreNum = false;
	});
	
	$("#p_creNum").blur(function() {
		checkCreNum(1);
	});
	$("#o_creNum").focus(function() {
		isRightOCreNum = false;
	});
	
	$("#o_creNum").blur(function() {
		checkCreNum(2);
	});
	$("#i_realName").blur(function() {
		if($.trim($("#i_realName").val()) == '') {
			$("#i_realName").focus();
			showErrMsg("i_realName","请输入真实姓名");
		}else{
			hideMsg("i_realName");
		}
	});
	$("#p_realName").blur(function() {
		if($.trim($("#p_realName").val()) == '') {
			$("#p_realName").focus();
			showErrMsg("p_realName","请输入真实姓名");
		}else{
			hideMsg("p_realName");
		}
	});
	$("#o_realName").blur(function() {
		if($.trim($("#o_realName").val()) == '') {
			$("#o_realName").focus();
			showErrMsg("o_realName","请输入真实姓名");
		}else{
			hideMsg("o_realName");
		}
	});
	
	$("#i_frontPic").uploadPreview({
		Img : "i_frontImg",
		Width : 100,
		Height : 100
	});
	$("#p_frontPic").uploadPreview({
		Img : "p_frontImg",
		Width : 100,
		Height : 100
	});
	$("#o_frontPic").uploadPreview({
		Img : "o_frontImg",
		Width : 100,
		Height : 100
	});
	$("#i_reversePic").uploadPreview({
		Img : "i_reverseImg",
		Width : 100,
		Height : 100
	});
	
	$("#i_frontPic").change(function() {
		if($(this).val() == '') {
			$("#i_frontImg").attr("src","");
			$("#i_fwSpan").removeClass("watermark");
			$("#i_fwSpan").html("请上传证件照(人像面)");
			$(this).parent().children("div[class='tip']").hide();
		}else if($("#creType option:selected").val() == "0" ){
			$("#i_frontPic").showLoading();
			var formData = new FormData();
            formData.append('cardType', 0);
            formData.append('file', this.files[0]);
            validateAuthImg(formData,0);
		}
	});
	$("#p_frontPic").change(function() {
		if($(this).val() == '') {
			$("#p_frontImg").attr("src","");
			$("#p_fwSpan").removeClass("watermark");
			$("#p_fwSpan").html("请上传证件照)");
			$(this).parent().children("div[class='tip']").hide();
		}
	});
	$("#o_frontPic").change(function() {
		if($(this).val() == '') {
			$("#o_frontImg").attr("src","");
			$("#o_fwSpan").removeClass("watermark");
			$("#o_fwSpan").html("请上传证件照");
			$(this).parent().children("div[class='tip']").hide();
		}
	});
	$("#i_reversePic").change(function() {
		if($(this).val() == '') {
			$("#i_reverseImg").attr("src","");
			$("#i_rwSpan").removeClass("watermark");
			$("#i_rwSpan").html("请上传证件照(国徽面)");
			$(this).parent().children("div[class='tip']").hide();
		}else if($("#creType option:selected").val() == "0" ){
			$("#i_reversePic").showLoading();
			var formData = new FormData();
            formData.append('cardType', 1);
            formData.append('file', this.files[0]);
            validateAuthImg(formData,1);
		}
	});
 

	$("#i_prev,#p_prev,#o_prev").click(function() {
		parent.$("#content").prop("src", "idAuthentication.html");
	});
	$("#p_next").click(function() {
		if ($.trim($("#p_realName").val()) == '') {
			$("#p_realName").focus();
			showErrMsg("p_realName", "请输入真实姓名");
			return;
		}
		if (!checkCreNum(1)) {
			return;
		}
		var frontPicVal = $("#p_frontPic").val();

		if (!existPRecord && frontPicVal == '') {
			layer.alert("请上传证件照");
			return;
		}
 
		if (frontPicVal != '') {
			if(!isPhone && !checkFileExt(frontPicVal)){
				layer.alert("证件照格式有误,请选择正确格式的图片");
				return;
			}
		}

		if (frontPicVal != '' && !lessMaxSize($("#p_frontPic")[0].files[0])) {
			layer.alert("证件照太大,请按照提示要求上传图片");
			return;
		}
 
		// 数据长度校验
		if ($("#p_realName").val().length > 50) {
			$("#p_realName").focus();
			showErrMsg("p_realName", "真实姓名输入过长,请精简");
			return;
		}

		if ($("#p_creNum").val().length > 200) {
			$("#p_creName").focus();
			showErrMsg("p_creNum", "证件号输入过长,请精简");
			return;
		}

		showLoading();
		$("#passportForm").ajaxSubmit( {
			url : rootPath + '/realNameTmp/replaceTmp',
			type : 'POST',
			contentType : 'application/json;charset=UTF-8',
			success : function(data) {
				hideLoading();
				if (data.returnCode == '0000') {
					var url = switchPage(creType, rleId);
					parent.$("#content").prop("src",url + "&currentPage=realNameAuth.html" + param);
				} else {
					layer.alert(data.returnMessage);
				}
			},
			error : function(jqXHR, textStatus,errorThrown) {
				hideLoading();
				layer.alert("error");
			}
		});
		return false;
	});
	
	$("#o_next").click(function() {
		if ($.trim($("#o_realName").val()) == '') {
			$("#o_realName").focus();
			showErrMsg("o_realName", "请输入真实姓名");
			return;
		}
		if (!checkCreNum(2)) {
			return;
		}
		var frontPicVal = $("#o_frontPic").val();

		if (!existORecord && frontPicVal == '') {
			layer.alert("请上传证件照");
			return;
		}
 
		if (frontPicVal != '') {
			if(!isPhone && !checkFileExt(frontPicVal)){
			layer.alert("证件照格式有误,请选择正确格式的图片");
			return;
			}
		}

		if (frontPicVal != '' && !lessMaxSize($("#o_frontPic")[0].files[0])) {
			layer.alert("证件照太大,请按照提示要求上传图片");
			return;
		}
 
		// 数据长度校验
		if ($("#o_realName").val().length > 50) {
			$("#o_realName").focus();
			showErrMsg("o_realName", "真实姓名输入过长,请精简");
			return;
		}

		if ($("#o_creNum").val().length > 200) {
			$("#o_creName").focus();
			showErrMsg("o_creNum", "证件号输入过长,请精简");
			return;
		}

		showLoading();
		$("#otherForm").ajaxSubmit( {
			url : rootPath + '/realNameTmp/replaceOtherTmp',
			type : 'POST',
			contentType : 'application/json;charset=UTF-8',
			success : function(data) {
				hideLoading();
				if (data.returnCode == '0000') {
					var url = switchPage(creType, rleId);
					parent.$("#content").prop("src",url + "&currentPage=realNameAuth.html" + param);
				} else {
					layer.alert(data.returnMessage);
				}
			},
			error : function(jqXHR, textStatus,errorThrown) {
				hideLoading();
				layer.alert("error");
			}
		});
		return false;
	});
	
	
});

function showErrMsg(id, message) {
	$("#" + id + "Msg").show();
	$("#" + id + "Tip").text(message);
}

function hideMsg(id) {
	$("#" + id + "Msg").hide();
}

function checkCreNum(idx) {
	var creType = $("#creType option:selected").val();
	var creNum = idx == 0?$("#i_creNum").val():idx ==1?$("#p_creNum").val():$("#o_creNum").val();
	if(creNum == '') {
		if(idx == 0){
			$("#i_creNum").focus();
			showErrMsg("i_creNum","请输入证件号");
			isRightICreNum = false;
			return isRightICreNum;
		}else if(idx == 1){
			$("#p_creNum").focus();
			showErrMsg("p_creNum","请输入证件号");
			isRightPCreNum = false;
			return isRightPCreNum;
		}else {
			$("#o_creNum").focus();
			showErrMsg("o_creNum","请输入证件号");
			isRightOCreNum = false;
			return isRightOCreNum;
		}
		 
	}
	
	//检查之前是否存在记录
	if(creType == oriCreType && creNum == oriCreNum) {
		if(idx == 0 && existRecord){
			isRightICreNum = true;	
			return isRightICreNum;
		}else if(idx == 1 && existPRecord){
			isRightPCreNum = true;
			return isRightPCreNum;
		}else if(idx == 2 && existORecord){
			isRightOCreNum = true;
			return isRightOCreNum;
		}else{
			return false; //  非法数据
		}
	}
	

	var regex;
	if(0 == creType) {
		regex = /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/;
		if(!regex.test(creNum)) {
			$("#i_creNum").focus();
			showErrMsg("i_creNum","身份证输入不合法");
			isRightICreNum = false;
			
		} else {
			//个人/团体 实名
			if(getUrlParam("creType") < 100) {				
				vaildateCreNum(creNum);
			}
			isRightICreNum = true;
		}
		return isRightICreNum;
	} else if(1 == creType || 2 == creType) {
//		regex = /^1[45][0-9]{7}|G[0-9]{8}|P[0-9]{7}|S[0-9]{7,8}|D[0-9]+$/;
//		if(!regex.test(creNum)) {
//			$("#p_creNum").focus();
//			showErrMsg("p_creNum","护照输入不合法");
//			isRightPCreNum = false;
//			//return;
//		} else {
			hideMsg("p_creNum");
			hideMsg("o_creNum");
			isRightPCreNum = true;
			isRightOCreNum = true;
//		}
		return isRightPCreNum; //return true 就可以了
	}
	
}

function focusById(){
	$("#i_realName").focus(function(){
		hideMsg("i_realName");
	});
	$("#i_creNum").focus(function(){
		hideMsg("i_creNum");
	});
	$("#p_realName").focus(function(){
		hideMsg("p_realName");
	});
	$("#p_creNum").focus(function(){
		hideMsg("p_creNum");
	});
	$("#o_realName").focus(function(){
		hideMsg("o_realName");
	});
	$("#o_creNum").focus(function(){
		hideMsg("o_creNum");
	});
}
function validateAuthImg(formData,idx){
	 $.ajax({
        url: rootPath + "/realNameAuth/vaildateAuthImg",
        type: "post",
        data: formData,
        contentType: false,
        processData: false,
        dataType:'json',
        mimeType: "multipart/form-data",
        success: function (data) {
       	 if( 0==idx ){
       		 $("#i_frontPic").hideLoading();
       	 }else{
       		 $("#i_reversePic").hideLoading();
       	 }
       	
       	 if('0000' == data.returnCode && data.returnObject != null) {
       		 
           	var ocr = data.returnObject;
           	if(ocr.ocrCode == "0"){
           		if(ocr.cardType == 0){
           			i_creFrontPic = ocr.filename;
           			hideMsg("i_realName");
           			hideMsg("i_creNum");
           			$("#i_realName").val(ocr.ocrName);
               		$("#i_creNum").val(ocr.ocrIdCard);
               		if(getUrlParam("creType") < 100 ) {
               			vaildateCreNum(ocr.ocrIdCard);
               		} else {
               			isRightICreNum = true; 
               		}
           		}else{
           			i_creReversePic = ocr.filename;
           		}
           	}else if(ocr.cardType == 0){
           		$("#i_realName").val("");
           		$("#i_creNum").val("");
           		isRightICreNum = false;
           		$("#i_creNumMsg").hide();
           		i_creFrontPic = null;
           		layer.alert("证件照（人像面）不规范或者不是身份证人像面！");
           	}else if(ocr.cardType == 1){
           		i_creReversePic= null;
           		layer.alert("证件照（国徽面）不规范或者不是身份证国徽面！");
           	} 
            
           }else{
           	if(0 == idx){
           		i_creFrontPic = null;
           		layer.alert("证件照（人像面）上传失败，请刷新重试！");
           	}else {
           		i_creReversePic= null;
           		layer.alert("证件照（国徽面）上传失败，请刷新重试！");
           	}
           	
           }
       	showIDButton();
        },
        error: function (e) {
            console.error(e)
        }
    });
}
//需改 下一步是否可点击
function showIDButton(){
	$("#i_next").css("background","#b4b4b4");
	$("#i_next").removeAttr("onclick");
	if(isRightICreNum &&( i_creFrontPic !=null && i_creReversePic!=null )){
		$("#i_next").css("background","rgb(197, 24, 10)");
		$("#i_next").attr("onclick","nextClick(0);");
	}
}
function vaildateCreNum(i_creNum){
	if(!i_creNum) return;
	$.ajax({
		url : rootPath + '/realNameAuth/vaildateCreNum/'+i_creNum,
		dataType: 'json',
		contentType : 'application/json;charset=UTF-8',
		success:function(res){
			if("1004" == res.returnCode){
				if(res.returnObject != null){
            		showErrMsg("i_creNum",res.returnObject);
        			isRightICreNum = false;
            	}else{
            		showErrMsg("i_creNum","身份证已被其他人使用！");
        			isRightICreNum = false;
            	}
			}else{
				isRightICreNum = true; 
			}
			showIDButton();
		},
		fail:function(){
			console.error("ajaxIdForm error");
		}
	});
}
//身份证下一步 nextClick(0) idx 未用
function nextClick(idx){
	if ($.trim($("#i_realName").val()) == '') {
		$("#i_realName").focus();
		showErrMsg("i_realName", "请输入真实姓名");
		return;
	}
	var frontPicVal = $("#i_frontPic").val();
	var reversePicVal = $("#i_reversePic").val();

	if (!existRecord && frontPicVal == '') {
		layer.alert("请上传证件照的人像面");
		return;
	}

	if (!existRecord && reversePicVal == '') {
		layer.alert("请上传证件照国徽面");
		return;
	}

	if (frontPicVal != '') {
		if(!isPhone && !checkFileExt(frontPicVal)){
		layer.alert("人像面证件照格式有误,请选择正确格式的图片");
		return;
		}
	}

	if (frontPicVal != '' && !lessMaxSize($("#i_frontPic")[0].files[0])) {
		layer.alert("人像面证件照太大,请按照提示要求上传图片");
		return;
	}

	if (reversePicVal != '') {
		if(!isPhone && !checkFileExt(reversePicVal)){
		layer.alert("国徽面证件照格式有误,请选择正确格式的图片");
		return;
		}
	}

	if (reversePicVal != '' && !lessMaxSize($("#i_reversePic")[0].files[0])) {
		layer.alert("国徽面证件照太大,请按照提示要求上传图片");
		return;
	}

	// 数据长度校验
	if ($("#i_realName").val().length > 50) {
		$("#i_realName").focus();
		showErrMsg("i_realName", "真实姓名输入过长,请精简");
		return;
	}

	if ($("#i_creNum").val().length > 200) {
		$("#i_creName").focus();
		showErrMsg("creNum", "证件号输入过长,请精简");
		return;
	}
	if (!checkCreNum(idx)) {
		return;
	}
	var authFormData = {};
	authFormData["creType"] = $("#creType option:selected").val();
	authFormData["realName"] = $("#i_realName").val();
	authFormData["creNum"] = $("#i_creNum").val();
	authFormData["creFrontPic"] = i_creFrontPic;
	authFormData["creReversePic"] = i_creReversePic;
	//请求开始
	$.ajax( {
		url : rootPath + '/realNameTmp/replaceIdCardTmp',
		type : 'POST',
		dataType: 'json',
		contentType : 'application/json;charset=UTF-8',
		data: JSON.stringify(authFormData),
		success : function(data) {
			hideLoading();
			if (data.returnCode == '0000') {
				var url = switchPage(creType, rleId);
				parent.$("#content").prop("src",url+ "&currentPage=realNameAuth.html" + param);
			} else {
				layer.alert(data.returnMessage);
			}
		},
		error : function(jqXHR, textStatus,errorThrown) {
			hideLoading();
			layer.alert("error");
		}
	});
}